import './App.css';
import { useEffect, useRef, useState } from 'react';
import axios from 'axios'; // 导入 Axios

function App() {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const audioRef = useRef(null); // 用于存储音频元素的引用
  const startButtonRef = useRef(null);
  const stopButtonRef = useRef(null);
  const switchButtonRef = useRef(null);
  const playAudioButtonRef = useRef(null);
  let captureInterval = null; // 用于存储定时器
  const [cameras, setCameras] = useState([]);
  const [currentCamera, setCurrentCamera] = useState(null);

  useEffect(() => {
    const startButton = startButtonRef.current;
    const stopButton = stopButtonRef.current;
    const switchButton = switchButtonRef.current;
    const playAudioButton = playAudioButtonRef.current;

    const getCameras = async () => {
      try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        const videoDevices = devices.filter(device => device.kind === 'videoinput');
        setCameras(videoDevices);
        if (videoDevices.length > 0) {
          setCurrentCamera(videoDevices[0].deviceId);
        }
      } catch (err) {
        console.error("无法获取摄像头设备", err);
      }
    };

    const startVideo = async () => {
      try {
        const constraints = { video: { deviceId: currentCamera } };
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          videoRef.current.play(); // 确保视频自动播放
        }
        // 启动定时器，每秒捕获一帧
        captureInterval = setInterval(captureFrame, 5000);
      } catch (err) {
        console.error("无法访问摄像头", err);
      }
    };

    const stopVideo = () => {
      console.log('stopVideo'); 
      if (videoRef.current) {
        const stream = videoRef.current.srcObject;
        if (stream) {
          const tracks = stream.getTracks();
          tracks.forEach(track => track.stop());
          videoRef.current.srcObject = null;
        }
      }
      // 清除定时器
      if (captureInterval) {
        clearInterval(captureInterval);
        captureInterval = null;
        console.log('定时器已清除'); 
      } else {
        console.log('没有定时器需要清除'); 
      }
    };

    const captureFrame = () => {
        const video = videoRef.current;
        const canvas = canvasRef.current;
        if (video && canvas) {
            const context = canvas.getContext('2d');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            console.log("帧数据已捕获");

            // 将帧数据转换为Base64字符串
            const dataURL = canvas.toDataURL('image/png');
            console.log("帧数据的Base64表示:", dataURL);

            // 将Base64字符串转换为Blob对象
            const blob = dataURLtoBlob(dataURL);
            if(blob === null){
              return;
            }

            // 创建FormData对象
            const formData = new FormData();
            formData.append('image', blob, 'frame.png');

            // 发送请求使用 Axios
            axios.post('https://sac.bluemz.cn:8443/person_detect', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(response => {
                console.log('成功:', response.data);
                if (response.data.count > 0) {
                    console.log('检测到人脸');
                } else {
                  playAudio();
                }
            })
            .catch((error) => {
                console.error('错误:', error);
            });
        }
    };

    const switchCamera = () => {
      const currentIndex = cameras.findIndex(camera => camera.deviceId === currentCamera);
      const nextIndex = (currentIndex + 1) % cameras.length;
      setCurrentCamera(cameras[nextIndex].deviceId);
      stopVideo();
      startVideo();
    };

    const playAudio = () => {
      if (audioRef.current) {
        audioRef.current.play().catch(error => {
          console.error("无法播放音频", error);
        });
      }
    };

    if (startButton) {
      startButton.addEventListener('click', startVideo);
    }

    if (stopButton) {
      stopButton.addEventListener('click', stopVideo);
    }

    if (switchButton) {
      switchButton.addEventListener('click', switchCamera);
    }

    if (playAudioButton) {
      playAudioButton.addEventListener('click', playAudio);
    }

    // 获取摄像头设备
    getCameras();

    // 清理事件监听器
    return () => {
      if (startButton) {
        startButton.removeEventListener('click', startVideo);
      }
      if (stopButton) {
        stopButton.removeEventListener('click', stopVideo);
      }
      if (switchButton) {
        switchButton.removeEventListener('click', switchCamera);
      }
      if (playAudioButton) {
        playAudioButton.removeEventListener('click', playAudio);
      }
      // 清除定时器
      if (captureInterval) {
        clearInterval(captureInterval);
        captureInterval = null;
      }
    };
  }, [cameras, currentCamera]);

  function dataURLtoBlob(dataURL) {
    if (dataURL.length < 100) {
      return null;
    }
    const arr = dataURL.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }

    return new Blob([u8arr], { type: mime });
  }

  return (
    <div className="App">
      <video ref={videoRef} id="camera" width={640} height={480} controls muted />
      <audio ref={audioRef} src="./audio/output.mp3" />
      <div className="button-container">
        <button ref={startButtonRef} id="startButton">开始</button>
        <button ref={stopButtonRef} id="stopButton">停止</button>
        <button ref={switchButtonRef} id="switchButton">切换摄像头</button>
        <button ref={playAudioButtonRef} id="playAudioButton">播放音频</button>
      </div>
      <canvas ref={canvasRef} style={{ display: 'none' }} />
    </div>
  );
}

export default App;